package com.tianji.remark.service.impl;

import com.tianji.api.dto.msg.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author LYY
 * @since 2025-05-14
 */
@Builder
@Service
@Slf4j
@RequiredArgsConstructor
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {
private final RabbitMqHelper rabbitMqHelper;
    @Override
    public void addLikeRecord(LikeRecordFormDTO dto) {
        // 获取当前登录用户
        Long userId = UserContext.getUser();
        // 判断是点赞还是取消点赞
        boolean flag = dto.getLiked() ? liked(dto, userId) : unliked(dto, userId);
        if (!flag) {
            // 说明点赞或者取消赞失败
            return;
        }
        // 统计该业务逻辑下的总点赞数
        Integer totalLikesNum = this.lambdaQuery()
                .eq(LikedRecord::getBizId, dto.getBizId())
                .count();

        // 发送消息到mq
        String routingKey = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE,dto.getBizType());
        // LikedTimesDTO.LikedTimesDTOBuilder msg = LikedTimesDTO.builder().bizId(dto.getBizId()).likedTimes(totalLikesNum);
        LikedTimesDTO msg = LikedTimesDTO.of(dto.getBizId(), totalLikesNum);
        log.debug("发送点赞消息 消息内容{}", msg);
        rabbitMqHelper.send(
                MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                routingKey,
                msg);
    }



    private boolean liked(LikeRecordFormDTO dto, Long userId) {
        LikedRecord record=this.lambdaQuery()
                .eq(LikedRecord::getUserId,userId)
                .eq(LikedRecord::getBizId,dto.getBizId())
                .one();
        if(record==null){
            //未点过赞 取消失败
            return false;
        }
        //删除点赞记录
        boolean result = this.removeById(record.getId());
        return result;
    }
    private boolean unliked(LikeRecordFormDTO dto, Long userId) {
        LikedRecord record=this.lambdaQuery()
                .eq(LikedRecord::getUserId,userId)
                .eq(LikedRecord::getBizId,dto.getBizId())
                .one();
        if(record!=null){
            return false;
        }
        //保存点赞记录到表中
        LikedRecord likeRecord=new LikedRecord();
        likeRecord.setUserId(userId);
        likeRecord.setBizId(dto.getBizId());
        likeRecord.setBizType(dto.getBizType());
        boolean result = this.save(likeRecord);
        return result;
    }
    @Override
    public Set<Long> getLikeStatusByBizIds(List<Long> bizIds) {
        if(CollUtils.isEmpty(bizIds)){
            return CollUtils.emptySet();
        }
        //获取用户id
        Long userId = UserContext.getUser();
        //查点赞记录表 in bizIds
        List<LikedRecord> recordList = this.lambdaQuery().in(LikedRecord::getBizId, bizIds).eq(LikedRecord::getUserId, userId).list();
        //将查询到的bizId转集合返回
        Set<Long> likeBizIds = recordList.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());
        return likeBizIds;
    }
}
